package org.linlinjava.litemall.event.handler;

import com.mzwise.tunnel.wx.builder.TextBuilder;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.linlinjava.litemall.db.domain.LitemallCouponUser;
import org.linlinjava.litemall.db.service.LitemallCouponUserService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.util.CouponUserConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class GiftCardHandler extends AbstractHandler {

    @Autowired
    private LitemallCouponUserService litemallCouponUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {
        String msg = String.format("type:%s, event:%s, key:%s",
            wxMessage.getMsgType(), wxMessage.getEvent(),
            wxMessage.getEventKey());
        String userCardCode = wxMessage.getUserCardCode();
        this.logger.info("用户转赠卡卷事件");
        this.logger.info("卡卷code: " + userCardCode);
        LitemallCouponUser couponUser = litemallCouponUserService.findByWxCode(userCardCode);
        if (couponUser!=null) { // 如果系统中有则处理
            if (couponUser.getStatus() != CouponUserConstant.STATUS_USABLE) {
                this.logger.error("卡卷已不可用但出现转增行为, 卡卷code: " + userCardCode);
                return null;
            }
            couponUser.setStatus(CouponUserConstant.STATUS_GIFTING);
            litemallCouponUserService.update(couponUser);
        }
        return new TextBuilder().build("转赠卡卷成功", wxMessage, weixinService);
    }

}
